#!/bin/sh -e

appFile="./home-server"
logFile="./running/app.log"
pidFile="./running/pid.txt"

start() {

    #判断app执行文件是否存在
    if [ ! -f "$appFile" ]; then
        echo "please compile the project"
        exit 0
    fi

    # 判断PID文件是否存在,存在提示程序正在运行
    if [ -f "$pidFile" ]; then
        echo "app already running and pid = \c" & cat $pidFile
        exit 0
    fi

    # 日志输出文件不存在就新建一个
    if [ ! -f "$logFile" ]; then
        touch $logFile
    fi

    nohup $appFile > $logFile 2>&1 &

    # 将应用的运行的PID保存起来
    echo $! > $pidFile
    echo "app start and pid = \c" & cat $pidFile
}

stop() {

    # 判断PID文件是否存在,存在提示程序正在运行
    if [ ! -f "$pidFile" ]; then
        echo "app has stopped"
        exit 0
    fi

    # 通过应用运行的PID杀死应用
    for i in `cat $pidFile`;
    do
        kill 9 $i
        echo "app stop by killing [pid=$i]"
    done

    # 删除PID文件，表示应用已经停止运行
    rm -rf $pidFile
}



case "$1" in

    start)
        start
        ;;

    stop)
        stop
        ;;

esac